package com.cooba.activitys.integral;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.cooba.R;
import com.cooba.adapter.IntegralDetailsAdapter;
import com.cooba.bean.IntegralDetailBean;
import com.cooba.pullTorefresh.PullToRefreshBase;
import com.cooba.pullTorefresh.PullToRefreshListView;
import com.cooba.utils.Constants;
import com.cooba.utils.ServerURL;
import com.cooba.utils.SharedPreferencesUtil;
import com.cooba.utils.Utils;
import com.cooba.views.loadview.LoadViewHelper;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/6/13.
 */
public class IntegralDetailsActivity extends AppCompatActivity implements View.OnClickListener {
    private ImageButton back_ib;
    private TextView exchange_tv;
    private TextView avaid_integral_tv;
    private PullToRefreshListView rListView;
    private IntegralDetailsAdapter mAdapter;
    private List<IntegralDetailBean.IntegralInfo> mIntegralList;
    private HttpUtils httpUtils;
    private RequestParams params;
    private String next_key = "0";
    private IntegralDetailBean integraldetailbean;
    private MyReciver myReceiver;
    private String allTotalIntegral;
    private LoadViewHelper helper;
    private boolean mIsFirstLoad=true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_integral_detail);
        allTotalIntegral=getIntent().getStringExtra("allTotalIntegral");

        PushAgent.getInstance(this).onAppStart();

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.UPDATE_DATA);
        myReceiver = new MyReciver();
        registerReceiver(myReceiver, intentFilter);
        initView();
        getIntegralData(true);
    }

    private void initView() {
        mIntegralList = new ArrayList<>();
        back_ib = (ImageButton) findViewById(R.id.integral_detail_back_ib);
        exchange_tv = (TextView) findViewById(R.id.integral_detail_exchange_tv);
        avaid_integral_tv = (TextView) findViewById(R.id.integral_detail_avaid_integral);
        initPullTorefresh();
        helper=Utils.initLoadViewHelper(rListView);
        back_ib.setOnClickListener(this);
        exchange_tv.setOnClickListener(this);
        setIntegralData();
    }

    private void setIntegralData() {
//        String allTotalIntegral = SharedPreferencesUtil.getData(this, "allTotalIntegral", "");
//        if (!TextUtils.isEmpty(allTotalIntegral)) {
//            avaid_integral_tv.setText(allTotalIntegral);
//        }
        avaid_integral_tv.setText(allTotalIntegral);
    }

    private void initPullTorefresh() {
        rListView = (PullToRefreshListView) findViewById(R.id.integral_detail_lv);
        rListView.setPullRefreshEnabled(false);
        rListView.setPullLoadEnabled(true);
        rListView.setScrollLoadEnabled(true); //设置滚动加载可用
        mAdapter = new IntegralDetailsAdapter(this, mIntegralList);
        rListView.getRefreshableView().setAdapter(mAdapter);
        rListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {//下拉刷新

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {//上拉加载
                getIntegralData(false);
            }
        });
    }

    private void getIntegralData(final boolean isFirst) {
        if (mIsFirstLoad){
            helper.showLoading("正在加载...");
        }
        httpUtils = new HttpUtils();
        params = new RequestParams();
        Log.d("wei", "next_key" + next_key);
        String login_id=SharedPreferencesUtil.getData(this,"login_id","");
        params.addBodyParameter("login_id", login_id);
        params.addBodyParameter("next_key", next_key);
        params.addBodyParameter("page_size", "10");
        String urlIntegrallist = ServerURL.httpUrl + ServerURL.integralList;
        httpUtils.send(HttpRequest.HttpMethod.POST, urlIntegrallist, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wei", "获取积分列表失败");
                Toast.makeText(IntegralDetailsActivity.this, "无网络!", Toast.LENGTH_SHORT).show();
                rListView.setHasMoreData(false);
                rListView.onPullDownRefreshComplete();
                rListView.onPullUpRefreshComplete();
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wei", "获取积分列表成功" + responseInfo.result);
                try {
                    integraldetailbean = new Gson().fromJson(responseInfo.result, IntegralDetailBean.class);
                    if (integraldetailbean.getSignList() != null&&integraldetailbean.getSignList().size()>0) {
                        if (isFirst) {
                            mAdapter.setList(integraldetailbean.getSignList());
                        } else {
                            mAdapter.addMoreData(integraldetailbean.getSignList());
                        }
                        if (integraldetailbean.getNext_key() == null) {
                            next_key = String.valueOf(integraldetailbean.getSignList().size() + Integer.parseInt(next_key));
                        } else {
                            next_key = integraldetailbean.getNext_key();
                        }
                        if (integraldetailbean.getSignList().size()<10){
                            rListView.setHasMoreData(false);
                        }
                        mIsFirstLoad = false;
                        helper.restore();
                    } else {
                        if (isFirst) {
                            helper.showEmpty("暂时没有数据", "重新加载", false, null);
                        } else {
                            Toast.makeText(IntegralDetailsActivity.this, "没有更多数据啦", Toast.LENGTH_SHORT).show();
                        }
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }finally {

                    rListView.onPullDownRefreshComplete();
                    rListView.onPullUpRefreshComplete();

                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.integral_detail_back_ib:
                finish();
                break;
            case R.id.integral_detail_exchange_tv:
                Intent intent=new Intent(this,GoodsExchangeActivity.class);
                startActivity(intent);
                finish();
                break;
            default:
                break;
        }
    }

    private class MyReciver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Constants.UPDATE_DATA)) {
               setIntegralData();
            }
        }
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (myReceiver != null) {
            unregisterReceiver(myReceiver);
        }
    }
}
